package com.lightboat.system.service.impl;

import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lightboat.common.enums.RoleEnum;
import com.lightboat.common.exception.ServiceException;
import com.lightboat.common.utils.DateUtils;
import com.lightboat.common.utils.SecurityUtils;
import com.lightboat.system.domain.CrmUserFollowRecord;
import com.lightboat.system.domain.CrmUserFollowRelation;
import com.lightboat.system.mapper.CrmOrderMapper;
import com.lightboat.system.mapper.CrmUserFollowRecordMapper;
import com.lightboat.system.mapper.CrmUserFollowRelationMapper;
import com.lightboat.system.service.ICrmUserFollowRecordService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 用户跟进记录Service业务层处理
 *
 * @author lightboat
 * @date 2025-08-22
 */
@Service
@RequiredArgsConstructor
public class CrmUserFollowRecordServiceImpl extends ServiceImpl<CrmUserFollowRecordMapper, CrmUserFollowRecord> implements ICrmUserFollowRecordService {

    private final CrmUserFollowRecordMapper crmUserFollowRecordMapper;
    private final CrmUserFollowRelationMapper crmUserFollowRelationMapper;
    private final CrmOrderMapper crmOrderMapper;

    /**
     * 查询用户跟进记录
     *
     * @param id 用户跟进记录主键
     * @return 用户跟进记录
     */
    @Override
    public CrmUserFollowRecord selectCrmUserFollowRecordById(Long id) {
        return crmUserFollowRecordMapper.selectById(id);
    }

    /**
     * 查询用户跟进记录列表
     *
     * @param crmUserFollowRecord 用户跟进记录
     * @return 用户跟进记录
     */
    @Override
    public List<CrmUserFollowRecord> selectCrmUserFollowRecordList(CrmUserFollowRecord crmUserFollowRecord) {
        return crmUserFollowRecordMapper.selectCrmUserFollowRecordList(crmUserFollowRecord);
    }

    /**
     * 新增用户跟进记录
     *
     * @param crmUserFollowRecord 用户跟进记录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertCrmUserFollowRecord(CrmUserFollowRecord crmUserFollowRecord) {
        crmUserFollowRecord.setCreateTime(DateUtils.getNowDate());
        CrmUserFollowRelation crmUserFollowRelation = new CrmUserFollowRelation();
        crmUserFollowRelation.setContactNextTime(crmUserFollowRecord.getContactNextTime());
        crmUserFollowRelation.setContactLastTime(crmUserFollowRecord.getCreateTime());
        crmUserFollowRelation.setContactLastContent(crmUserFollowRecord.getFollowRemark());
        crmUserFollowRelationMapper.update(crmUserFollowRelation,
                Wrappers.<CrmUserFollowRelation>lambdaQuery()
                        .eq(CrmUserFollowRelation::getUserId, crmUserFollowRecord.getUserId())
                        .eq(CrmUserFollowRelation::getCustomerId, crmUserFollowRecord.getCustomerId())
        );
        return crmUserFollowRecordMapper.insert(crmUserFollowRecord);
    }

    /**
     * 修改用户跟进记录
     *
     * @param crmUserFollowRecord 用户跟进记录
     * @return 结果
     */
    @Override
    public int updateCrmUserFollowRecord(CrmUserFollowRecord crmUserFollowRecord) {
        crmUserFollowRecord.setUpdateTime(DateUtils.getNowDate());
        return crmUserFollowRecordMapper.updateById(crmUserFollowRecord);
    }

    /**
     * 批量删除用户跟进记录
     *
     * @param ids 需要删除的用户跟进记录主键
     * @return 结果
     */
    @Override
    public int deleteCrmUserFollowRecordByIds(Long[] ids) {
        return crmUserFollowRecordMapper.deleteCrmUserFollowRecordByIds(ids);
    }

    /**
     * 删除用户跟进记录信息
     *
     * @param id 用户跟进记录主键
     * @return 结果
     */
    @Override
    public int deleteCrmUserFollowRecordById(Long id) {
        return crmUserFollowRecordMapper.deleteCrmUserFollowRecordById(id);
    }

    @Override
    public List<CrmUserFollowRecord> selectCrmUserFollowRecordList(Wrapper<?> wrapper) {
        return crmUserFollowRecordMapper.selectCrmUserFollowRecord(wrapper);
    }


    @Override
    public LambdaQueryWrapper<CrmUserFollowRecord> getQueryWrapper(CrmUserFollowRecord crmUserFollowRecord) {
        /**
         * 是这样的：
         关于备注逻辑：
         销售能看到 订单中【其他销售人员公开的备注 和 自己的备注】
         客服同理 订单中【其他销售人员公开的备注 和 自己的备注】
         销售也能点击客服得备注弹窗，但是只能看到 公开的，不能发表 只能看
         客服也能看销售的弹窗，也是只有公开的，不能发表 只能看
         超管可以给所有人备注，但是不公开的，也是除了自己 谁也看不到
         超管可以看到所有的人备注（不公开的也能看到）
         * typeCode：1 客服 2 销售
         */
        LambdaQueryWrapper<CrmUserFollowRecord> wrapper = Wrappers.<CrmUserFollowRecord>lambdaQuery();
        wrapper.eq(ObjUtil.isNotEmpty(crmUserFollowRecord.getOrderId()), CrmUserFollowRecord::getOrderId, crmUserFollowRecord.getOrderId());
        wrapper.eq(ObjUtil.isNotEmpty(crmUserFollowRecord.getCustomerId()), CrmUserFollowRecord::getCustomerId, crmUserFollowRecord.getCustomerId());
        wrapper.eq(ObjUtil.isNotEmpty(crmUserFollowRecord.getTopStatus()), CrmUserFollowRecord::getTopStatus, crmUserFollowRecord.getTopStatus());
        wrapper.eq(ObjUtil.isNotEmpty(crmUserFollowRecord.getIsFollowed()), CrmUserFollowRecord::getIsFollowed, crmUserFollowRecord.getIsFollowed());
        wrapper.like(ObjUtil.isNotEmpty(crmUserFollowRecord.getFollowRemark()), CrmUserFollowRecord::getFollowRemark, crmUserFollowRecord.getFollowRemark());
        if (SecurityUtils.hasRole(RoleEnum.ADMIN.getRoleCode()) || SecurityUtils.hasRole(RoleEnum.BOSS.getRoleCode()) || SecurityUtils.hasRole(RoleEnum.SALE_MANAGER.getRoleCode()) || SecurityUtils.hasRole(RoleEnum.CUSTOMER_SERVICE.getRoleCode())) {
            wrapper.eq(CrmUserFollowRecord::getTypeCode, crmUserFollowRecord.getTypeCode());
        }else {
            if (ObjUtil.isNotEmpty(crmUserFollowRecord.getTypeCode())) {
                wrapper.and(a -> {
                    a.eq(CrmUserFollowRecord::getTypeCode, crmUserFollowRecord.getTypeCode())
                            .or(o -> {
                                o.eq(CrmUserFollowRecord::getTypeCode, crmUserFollowRecord.getTypeCode())
                                        .eq(CrmUserFollowRecord::getIsPrivate, 0);
                            });
                });
            } else {
                throw new ServiceException("类型CODE不能为空");
            }
        }
        return wrapper;
    }

    @Override
    public CrmUserFollowRecord getLatestRecord(CrmUserFollowRecord crmUserFollowRecord) {
        LambdaQueryWrapper<CrmUserFollowRecord> wrapper = getQueryWrapper(crmUserFollowRecord);
        wrapper.orderByDesc(CrmUserFollowRecord::getCreateTime,CrmUserFollowRecord::getFollowTime);
        wrapper.last("limit 1");
        return crmUserFollowRecordMapper.selectOne(wrapper);
    }
}
